<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils'
export default {
  name: 'Excel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 1. 将excel文件中的数据读取处理转化为js数据
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // console.log('results', results) // 内容
      // console.log('header', header) // 表头
      //  2. 将excel读取出来的数据进行格式化处理(中文转英文)
      const data = this.transToExecl(results)
      // console.log('data', data)
      // 3. 发送axios请求批量添加数据(格式化之后的数据)
      this.doAdd(data)
    },
    async doAdd(data) {
      try {
        await importEmployee(data)
        // console.log('importEmployee', res)
        this.$router.back()
        // 保存数据
      } catch (err) {
        console.log('importEmployee', err)
      }
    },
    transToExecl(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const result = data.map(zhObj => {
        // zhObj ==> {
        //  入职时间:44505,
        // 姓名:"小张",
        // 工号:"9002",
        //  ...
        // }
        const zhKeys = Object.keys(zhObj) // ['入职日期','姓名','工号','手机号','转正日期','部门']
        const enkeyObj = {} // 存储英文key的对象数据
        zhKeys.forEach(zhkey => {
          const enkey = mapInfo[zhkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enkeyObj[enkey] = formatExcelDate(zhObj[zhkey])
          } else {
            enkeyObj[enkey] = zhObj[zhkey]
          }
        })
        return enkeyObj
      })
      return result
    }
  }
}
</script>
